// abnormallyReport.js
var app = getApp();
var url = app.url;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    faultDescription: "",
    canRemark: false,
    str1: ['a'],
    str2: 'a',
    facilitiesNo: '',//设施编号
    streetLampType: '',//路灯类型
    address: '',//地址
    jwdInfo: '',//经纬度
    // powerUnit: '',//权属单位
    name: wx.getStorageSync('nickname'),
    phone: '',
    deptid: 0,//部门id
    loading: false,
    userInfo: {},
    exlist: [],
    radioVal: '',
    exobj: {},
    moreChflag: true,
    id: '',
    type: 0,
    tittleInfo: '',
    mapshow: true,
    remark: '',
    streetLampId: '',
    hasScene: false,
    imgshow:[],
    imgUrl:[],
    info: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
    this.setData({ id: options.id})
    this.checkLogin()
    this.getDetail()
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getUserInfo();
    var that = this;
    var scene = that.data.id;
    if (scene != '') {
      //查询故障信息
      // that.searchEX(scene);
    } else {
      //需要登录系统账号信息
      // that.checkLogin();
    }
  },
  onShareAppMessage: function () {

  },
  getUserInfo: function () {
    var that = this
    wx.getUserInfo({
      lang: 'zh_CN',
      success: function (res) {

      },
      fail: function (res) {
        wx.showModal({
          title: '需要您授权才能正常显示',
          content: '请点击“去授权”并点击授权按钮，即可正常使用',
          confirmText: '去授权',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              // wx.openSetting({
              //   success: function (re) {
              //     if (!re.authSetting["scope.userInfo"] || !re.authSetting["scope.userLocation"]) {
              //       var isset = that.data.isSetUserInfo
              //       if(!isset){
              //         that.getUserInfo()
              //       }
              //     }else{
              //       that.setData({ isSetUserInfo : true})
              //     }
              //   }
              // })
              console.log("用户点击确定")
              wx.navigateTo({
                url: '../authorize/authorize',
              })
            }
          }
        })
      }
    })
  },
  checkLogin: function () {
    var name = wx.getStorageSync('userName');
    if (name == '' || name == null) {
      wx.showModal({
        title: '提示',
        content: "用户未登录",
        confirmText: '去登录',
        showCancel: false,
        success: function () {
          wx.navigateTo({
            url: '../login/login',
          })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  //当获取焦点时触发
  focusFun: function (e) {
    var that = this;
    var param = e.target.dataset.param;
    that.searchEXlist();
    var val = 0;
    var tittle = '终端编号选择';
    if (param == 1) {
      val = 1;
      tittle = '终端编号选择';
    } else if (param == 3) {
      val = 3;
      tittle = '地址选择';
    } else if (param == 4) {
      val = 4;
      tittle = '经纬度选择';
    }
    that.setData({ type: val, tittleInfo: tittle });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  getDetail(){
    var that = this;
    var params = { reportId: this.data.id };
    wx.request({
      url: url + '/web/exceptionReport/getExceptionReportById.htm',
      data: app.ecbEncrypto(params),
      method: 'POST',
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr);
        console.log(rest)
        if (rest.isSuccess == 0) {
          var info = rest.reportInfo;
          info.imgList = info.imgUrl?info.imgUrl.split(","):[]
          info.imgList.forEach((item,index,arr)=>{
            arr[index] = that.data.imgurl + item
          })
          console.log(info.imgList)
          info.createTime = new Date(info.createTime).Format("yyyy-MM-dd hh:mm:ss");
          try {
            info.additionalNote = info.additionalNote ? JSON.parse(info.additionalNote) : []
          } catch (error) {
            info.additionalNote = info.additionalNote ? JSON.parse(info.additionalNote.replace(/"imgUrl":".*?","time":"/gs, '"time":"')) : []
          }
          that.setData({ info: info })
        } else {
          wx.showModal({
            title: '提示',
            content: rest.errorMsg,
            showCancel: false
          })
        }
      },

    })
  },
  openMap: function (event) {
    var that=this 
    wx.chooseLocation({
      success(res){
        console.log(res)
        that.setData({
          liveArea: res.address,
          address: res.address,
          jwdInfo: `${res.longitude},${res.latitude}`
        })
      },
      fail(res){
        console.log(res)
      }
    })
  },
  //为空判断
  getValue: function (e) {
    var that = this;
    var param = e.target.dataset.param;
    var val = e.detail.value;
    if (param == 1) {
      that.setData({ facilitiesNo: val.trim() });
    } else if (param == 2) {
      that.setData({ streetLampType: val.trim() });
    } else if (param == 3) {
      that.setData({ address: val.trim() });
    } else if (param == 4) {
      that.setData({ jwdInfo: val.trim() });
    }
    // else if (param == 5){
    //   that.setData({ powerUnit: val.trim() });
    // } 
    else if (param == 6) {
      that.setData({ name: val.trim() });
    } else if (param == 7) {
      that.setData({ phone: val.trim() });
    } else if (param == 8) {
      that.setData({ remark: val.trim() });
    }
  },
 
  exsubmit: function (type) {
    var that = this;
    var id = this.data.id;
    const current = {
      userName: wx.getStorageSync('userName'),
      nickname: wx.getStorageSync('nickname'),
      remark: this.data.remark,
      userId: wx.getStorageSync('userId'),
      imgUrl: this.data.imgUrl.toString(),
      time: js_date_time(new Date().getTime()),
      address: this.data.address,
      lnglat:this.data.jwdInfo
    }
    const bclist = this.data.info.additionalNote || [];
    var params = {
      id,
      additionalNote: JSON.stringify([...bclist,current])
    };
    if (!current.remark) {
      wx.showToast({
        title: '请填写详细描述',
        image: '../../images/error.png',
        duration: 2000,
        mask: true
      })
      return false;
    }
    console.log(params)
    console.log(app.ecbEncrypto(params))
    wx.request({
      url: url + '/web/exceptionReport/setAdditionalNote.htm',
      data: app.ecbEncrypto(params),
      method: 'POST',
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr);
        console.log(rest)
        if (rest.isSuccess == 0) {
          wx.navigateBack({ delta: 2 })
        } else {
          wx.showModal({
            title: '提示',
            content: rest.errorMsg,
            showCancel: false
          })
        }
      },

    })
  },
  clickFun: function (e) {
    var id = e.currentTarget.dataset.id;
    var ob = e.currentTarget.dataset.ob;
    this.setData({ radioVal: id, exobj: ob });
  },
  sureButton: function () {
    var that = this;
    that.setData({
      moreChflag: true,
      facilitiesNo: that.data.exobj.meterAddr,
      address: that.data.exobj.address,
      jwdInfo: that.data.exobj.lngLat,
      deptid: that.data.exobj.deptid,
      streetLampType: that.data.exobj.streetLampType,//路灯类型
      // powerUnit: that.data.exobj.powerUnit,//权属单位
      streetLampId: that.data.exobj.id
    });
  },
  hideMoreCh: function () {
    this.setData({ moreChflag: true })
  },
  mapshow: function () {
    this.setData({ mapshow: !this.data.mapshow })
  },
  chooseImage(e) {
    var that = this;
    var header = {
      'content-type': 'application/x-www-form-urlencoded',
      'Accept-Encoding': 'gzip, deflate',
      'Accept-Language': 'zh-CN,zh; q=0.8',
      'Accept': '*/*',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'Content-Length': '64',
      'Pragma': 'no-cache',
    };
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths;

        tempFilePaths.forEach((item,index)=>{
          if(index < 5){
            wx.uploadFile({
              url: app.url + '/api/account/wxupload.htm',
    
              filePath: item,
              name: 'file',
              formData: {
                'user': 'test'
              },
              success(res) {
                console.log(res.data)
                var imgUrlList = that.data.imgUrl
                imgUrlList = imgUrlList.concat([res.data])
    
                var imgshowList = that.data.imgshow;
                imgshowList = imgshowList.concat([item])
  
                that.setData({
                  imgUrl: imgUrlList,
                  imgshow: imgshowList,
                })
              }
            })
          }
          
        })

        console.log(tempFilePaths);

        

      }
    })
  },
  callPhone() {
    wx.makePhoneCall({
      phoneNumber: '86881114',
    })
  },
  deleteImg(e){
    var index = e.currentTarget.dataset.index;
    var imgUrlList = this.data.imgUrl
    var imgshowList = this.data.imgshow;
    imgUrlList.splice(index,1)
    imgshowList.splice(index,1)    
    this.setData({
      imgUrl:imgUrlList,
      imgshow:imgshowList,
    })
  }
})

function js_date_time(unixtime) {
  var dateTime = new Date(parseInt(unixtime))
  var year = dateTime.getFullYear();
  var month = (dateTime.getMonth() + 1) < 10 ? "0" + (dateTime.getMonth() + 1) : (dateTime.getMonth() + 1);
  var day = dateTime.getDate() < 10 ? "0" + dateTime.getDate() : dateTime.getDate();
  var hour = dateTime.getHours() < 10 ? "0" + dateTime.getHours() : dateTime.getHours();
  var minute = dateTime.getMinutes() < 10 ? "0" + dateTime.getMinutes() : dateTime.getMinutes();
  var second = dateTime.getSeconds();
  var now = new Date();
  var now_new = Date.parse(now.toDateString());  //typescript转换写法
  var milliseconds = now_new - dateTime;
  var timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
  return timeSpanStr;
}

Date.prototype.Format = function (fmt) { //author: meizz  
  var o = {
    "M+": this.getMonth() + 1, //月份  
    "d+": this.getDate(), //日  
    "h+": this.getHours(), //小时  
    "m+": this.getMinutes(), //分  
    "s+": this.getSeconds(), //秒  
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度  
    "S": this.getMilliseconds() //毫秒  
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
};